package prosjekt;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;


@SuppressWarnings("serial")
public class LeveringsBetalingForm extends JPanel {
	private JTable ordreTable;
	private Timer 	timer;
	private DetailAndPay	numPad;
	

	public LeveringsBetalingForm() {
		super(new GridBagLayout());
		setPreferredSize(new Dimension(1029,670));
		initGUI();
		setVisible(true);
	}

	private void initGUI() {
		GridBagConstraints c = new GridBagConstraints();
		
		DefaultTableModel dtm = new DefaultTableModel(){
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		dtm.addColumn("Nr.");
		dtm.addColumn("Kunde navn");
		
		ordreTable = new JTable();
		ordreTable.setModel(dtm);
		ordreTable.getColumnModel().getColumn(0).setPreferredWidth(15);
		ordreTable.setFillsViewportHeight(true);

		ordreTable.getTableHeader().setResizingAllowed(false);
		ordreTable.getTableHeader().setReorderingAllowed(false);
		ordreTable.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e) {
				displaySelected();
			}
		});

		JScrollPane jsp = new JScrollPane(ordreTable);
		jsp.setBorder(BorderFactory.createEtchedBorder());
		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		jsp.setPreferredSize(new Dimension(250,685));
		
		c.anchor = GridBagConstraints.WEST;
		c.gridx = 0;
		c.gridy = 0;
		c.gridheight = GridBagConstraints.REMAINDER;
		add(jsp, c);
		
		c.anchor = GridBagConstraints.SOUTH;
		c.gridx = 1;
		numPad = new DetailAndPay();
		add(numPad,c);
		
		timer = new Timer(10000, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				updateOrdreListe();
			}
		});
		timer.setInitialDelay(0);
		timer.start();
	}
	
	/**
	 * Updates the list of orders with fresh info
	 */
	private void updateOrdreListe(){ 
		DefaultTableModel dtm = ((DefaultTableModel)ordreTable.getModel());
		
		//Remove old info
		int nr = dtm.getRowCount()-1;
		for(int i = nr; i >= 0; i--){
			dtm.removeRow(i);
		}
		
		try {
			ResultSet rs = RestaurantDB.getKunderUtenLevering();
			
			//Add new info
			while (rs.next()){
				((DefaultTableModel)ordreTable.getModel()).addRow(new Object[]{rs.getInt(1),""+rs.getString(3)+" "+rs.getString(2)});
			}
		} catch (SQLException e) {
			return;
		}
		revalidate();
	}
	
	/**Displays the selected order with more detail*/
	private void displaySelected(){
		int row =ordreTable.getSelectedRow();
		if( row < ordreTable.getRowCount() && row >= 0){			
			int ordreID = (Integer)ordreTable.getModel().getValueAt(row, 0);
			String navn = (String)ordreTable.getModel().getValueAt(row, 1);
			List<String> varer = new LinkedList<String>();
			int sum = 0;
			try {
				ResultSet rs = RestaurantDB.getUtleveringsOrdre(ordreID);

				while (rs.next()){
					int i = rs.getInt(2);
					varer.add(rs.getString(1)+"\t"+i);
					sum += i;
				}

			} catch (SQLException e) {
				return;
			}
			numPad.fillProduktListe(ordreID, navn, varer, sum);
		}
	}
	
	private class DetailAndPay extends JPanel{
		private JTextArea	produktListe	= new JTextArea();
		private JTextField	sum			 	= new JTextField("0");
		private int			selectedOrdreID = -1;
		int tottalt = 0;
		Color defaultColor;

		private JButton button1 = new JButton("1");
		private JButton button2 = new JButton("2");
		private JButton button3 = new JButton("3");
		private JButton button4 = new JButton("4");
		private JButton button5 = new JButton("5");
		private JButton button6 = new JButton("6");
		private JButton button7 = new JButton("7");
		private JButton button8 = new JButton("8");
		private JButton button9 = new JButton("9");
		private JButton button0 = new JButton("0");
		private JButton buttonCleare = new JButton("Cleare");
		private JButton buttonStore  = new JButton("Store");
		
		public DetailAndPay() {
			super(new GridBagLayout());
			initGUI();	
		}
		
		/**Sets up the GUI*/
		private void initGUI() {
			GridBagConstraints c = new GridBagConstraints();
			
			ActionListener al = new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					String gSum = sum.getText();
					int add;
					Object s = e.getSource();
					
					if(		s.equals(button1))	add = 1;
					else if(s.equals(button2))	add = 2;
					else if(s.equals(button3))	add = 3;
					else if(s.equals(button4))	add = 4;
					else if(s.equals(button5))	add = 5;
					else if(s.equals(button6))	add = 6;
					else if(s.equals(button7))	add = 7;
					else if(s.equals(button8))	add = 8;
					else if(s.equals(button9))	add = 9;
					else /*(s.equals(button0))*/add = 0; 
					
					
					if(gSum.isEmpty() || Integer.parseInt(gSum) != 0)
						sum.setText(sum.getText()+add);
					else 
						sum.setText(""+add);
				}
			};
			
			defaultColor = getBackground();
			button1.setPreferredSize(new Dimension(80,40));
			button2.setPreferredSize(new Dimension(80,40));
			button3.setPreferredSize(new Dimension(80,40));
			button4.setPreferredSize(new Dimension(80,40));
			button5.setPreferredSize(new Dimension(80,40));
			button6.setPreferredSize(new Dimension(80,40));
			button7.setPreferredSize(new Dimension(80,40));
			button8.setPreferredSize(new Dimension(80,40));
			button9.setPreferredSize(new Dimension(80,40));
			button0.setPreferredSize(new Dimension(80,40));
			buttonCleare.setPreferredSize(new Dimension(80,40));
			buttonStore. setPreferredSize(new Dimension(80,40));
			
			button1.addActionListener(al);
			button2.addActionListener(al);
			button3.addActionListener(al);
			button4.addActionListener(al);
			button5.addActionListener(al);
			button6.addActionListener(al);
			button7.addActionListener(al);
			button8.addActionListener(al);
			button9.addActionListener(al);
			button0.addActionListener(al);
			
			buttonCleare.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					selectedOrdreID = -1;
					produktListe.setText("");
					sum.setText("0");
					sum.setBackground(defaultColor);
				}
			});
			
			buttonStore.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					try {
						if(tottalt <= Integer.parseInt(sum.getText())){
							RestaurantDB.setOrdreLevert(selectedOrdreID);
							JOptionPane.showMessageDialog(null, produktListe.getText().substring(0, produktListe.getText().length()-10), "Kvittering", 1);
							
							PrinterJob pj = PrinterJob.getPrinterJob();
							pj.setPrintable(new PrintUI(produktListe.getText()));
							if(pj.printDialog())
								try {
									pj.print();
								} catch (PrinterException e1) {	}							
							selectedOrdreID = -1;
							produktListe.setText("");
							
							sum.setText(""+(tottalt - Integer.parseInt(sum.getText())));
							sum.setBackground(defaultColor);
						}else{
							sum.setBackground(Color.red);
						}
					} catch (SQLException e1) {	}
				}
			});

			produktListe.setPreferredSize(new Dimension(240,460));
			produktListe.setBorder(BorderFactory.createEtchedBorder());
			produktListe.setEditable(false);
			produktListe.setMargin(new Insets(10,100,10,10));
			
			sum.setPreferredSize(new Dimension(240,40));
			sum.setBorder(BorderFactory.createEtchedBorder());
			sum.setEditable(false);
			sum.setHorizontalAlignment(JTextField.RIGHT);
			//Enlarge font
			Font f = sum.getFont();
			sum.setFont(new Font(f.getName(),f.getStyle(), 30));
			
			//Adding buttons
			c.gridwidth = GridBagConstraints.REMAINDER;

			c.gridx= 0; 	c.gridy= 0; 	add(produktListe,c);
			c.gridx= 0; 	c.gridy= 1; 	add(sum,c);
			
			c.gridwidth = 1; 
			
			c.gridx= 0;		c.gridy= 2;		add(button1,c);
			c.gridx= 1;		c.gridy= 2;		add(button2,c);
			c.gridx= 2;		c.gridy= 2;		add(button3,c);
			c.gridx= 0;		c.gridy= 3;		add(button4,c);
			c.gridx= 1;		c.gridy= 3;		add(button5,c);
			c.gridx= 2;		c.gridy= 3;		add(button6,c);
			c.gridx= 0;		c.gridy= 4;		add(button7,c);
			c.gridx= 1;		c.gridy= 4;		add(button8,c);
			c.gridx= 2;		c.gridy= 4;		add(button9,c);
			c.gridx= 1;		c.gridy= 5;		add(button0,c);
			c.gridx= 0;		c.gridy= 5;		add(buttonCleare,c);
			c.gridx= 2;		c.gridy= 5;		add(buttonStore,c);
		}
		
		public void fillProduktListe(int ordreID, String navn, List<String> varer, int sum){
			int mva = (int) (sum*0.23);
			tottalt = sum+mva;
			
			StringBuffer sb = new StringBuffer();
			sb.append(navn+"\n"+"Ordre ID:   "+ordreID+"\n----------------------\n\n");
			for(String s : varer){
				sb.append(s+"\n");
			}
			sb.append("\n----------------------\n");
			sb.append("Sum:      "+sum+"\n");
			sb.append("Mva.:     "+(mva)+"\n");
			sb.append("Totalt:   "+(tottalt)+"\n");
			sb.append("\n======================\n");
			selectedOrdreID = ordreID;
			this.sum.setText("0");
			produktListe.setText(sb.toString());
			
		}
	}
}
